<template>
  <Card class="search">
    <Row class="operation">
      <Button size="large" type="primary" icon="md-add" @click="openModal('add',{})">添加角色</Button>
      <Button size="large" icon="md-trash">批量删除</Button>
      <Dropdown>
        <Button size="large">
          更多操作
          <Icon type="ios-arrow-down"></Icon>
        </Button>
        <DropdownMenu slot="list">
          <span @click="listRoleAllByPage"><DropdownItem>刷新</DropdownItem></span>
          <DropdownItem>重置用户密码</DropdownItem>
          <DropdownItem>导出所选数据</DropdownItem>
          <DropdownItem> 导出全部数据</DropdownItem>
          <DropdownItem>导入数据</DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <Button size="large" type="dashed">关闭搜索</Button>
      <Button size="large" type="dashed">关闭提示</Button>
    </Row>
    <Alert show-icon>已选择 <a>{{selectCount}}</a> 项 <a @click="clear">清空</a></Alert>
    <Table :columns="roleColumns" ref="table" :data="roleList" border draggable size="small">
      <template slot-scope="{row,index}" slot="setDefault">
        <Button :type="row.defaultRole?'primary':'warning'" size="small" style="margin-right: 5px"
                @click="row.defaultRole?'':setDefault(row)">{{row.defaultRole?'默认':'设为默认'}}
        </Button>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <Button type="warning" size="small" style="margin-right: 5px" @click="getPerTree(row)">菜单权限</Button>
        <Button type="success" size="small" style="margin-right: 5px" @click="show(index)">数据权限</Button>
        <Button type="primary" size="small" style="margin-right: 5px" @click="openModal('edit',row)">编辑</Button>
        <Button type="error" size="small" @click="removeRole([row.id])">删除</Button>
      </template>
    </Table>
    <div style="margin: 10px;overflow: hidden">
      <div style="float: right;">
        <Page :total="page.total" :current="page.pageNum" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size="page.pageSize" show-total show-elevator show-sizer/>
      </div>
    </div>
    <Modal v-model="roleModal.value" :title="roleModal.title">
      <Form ref="role" v-model="role" :label-width="70">
        <FormItem label="角色名称">
          <Input placeholder="请输入角色名称" v-model="role.name">
            <span slot="prepend">ROLE_</span>
          </Input>
        </FormItem>
        <FormItem label="备注">
          <Input type="textarea" v-model="role.common"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="addCancel">取消</Button>
        <Button type="primary" @click="editRole">提交</Button>
      </div>
    </Modal>
    <Modal v-model="roleMenuModal.value" :title="roleMenuModal.title">
      <Tree :data="menuTree" show-checkbox ref="menuTree" :check-strictly="true"></Tree>
      <div slot="footer">
        <Button @click="selectedAll">全选/反选</Button>
        <Button @click="roleMenuModal.value=false">取消</Button>
        <Button @click="resetRolePer">确定</Button>
      </div>
    </Modal>
  </Card>
</template>

<script>
import {
  selectRoleAllByPage,
  addRole,
  deleteRole,
  editRole,
  setDefault,
  getRolePerTree,
  resetRolePer
} from '@/api/user-api.js'

export default {
  name: 'role_list',
  data () {
    return {
      roleMenuModal: {
        value: false,
        title: ''
      },
      roleModal: {
        value: false,
        title: '添加角色',
        type: 'add'
      },
      page: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      drop: false,
      selectCount: 0,
      dropDownContent: '展开',
      dropDownIcon: 'ios-arrow-down',
      roleColumns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '角色名称',
          key: 'name',
          sortable: true,
          ellipsis: true,
          tooltip: true,
          resizable: true,
          width: 200
        },
        {
          title: '备注',
          key: 'common',
          sortable: true,
          ellipsis: true,
          tooltip: true,
          resizable: true,
          width: 500
        },
        {
          title: '创建时间',
          key: 'createTime',
          sortable: true,
          ellipsis: true,
          tooltip: true,
          resizable: true,
          width: 200
        },
        {
          title: '更新时间',
          key: 'updateTime',
          sortable: true,
          ellipsis: true,
          tooltip: true,
          resizable: true,
          width: 200
        },
        {
          title: '是否设置为注册用户默认角色',
          key: 'defaultRole',
          slot: 'setDefault',
          sortable: true,
          ellipsis: true,
          tooltip: true,
          resizable: true,
          width: 400
        }, {
          title: '操作',
          slot: 'action',
          width: 300,
          align: 'center',
          fixed: 'right'
        }
      ],
      roleList: [{
        id: '1',
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        common: null,
        delFlag: 0,
        name: 'ROLE_ADMIN',
        defaultRole: ''
      }],
      role: {},
      menuTree: [],
      selectRoleId: ''
    }
  },
  created () {
    this.listRoleAllByPage()
  },
  methods: {

    /**
       * 重置菜单权限
       */
    resetRolePer () {
      let data = {
        roleId: this.selectRoleId,
        perIds: []
      }
      this.$refs.menuTree.getCheckedAndIndeterminateNodes().forEach(v => {
        data.perIds.push(v.id)
      })
      resetRolePer(data).then(res => {
        if (res.code === 200) {
          this.roleMenuModal.value = false
          this.$Message.success(res.msg)
        } else {
          this.$Message.warning(res.msg)
        }
      })
    },
    selectedAll (tree) {
    },
    /**
       *设为默认角色
       */
    setDefault (row) {
      setDefault(row.id).then(res => {
        if (res.code === 200) {
          this.$Message.info(res.msg)
          this.listRoleAllByPage()
        } else {
          this.$Message.warning(res.msg)
        }
      }).catch(err => {
        this.$Message.error('添加失败,服务器失败')
      })
    },
    /**
       * 修改,添加 角色
       */
    editRole () {
      this.role.name = 'ROLE_' + this.role.name
      let re
      if (this.roleModal.type === 'add') {
        re = addRole(this.role)
      } else {
        re = editRole(this.role)
      }
      re.then(res => {
        if (res.code === 200) {
          this.$Message.info(res.msg)
          this.listRoleAllByPage()
          this.$refs.role.resetFields()
          this.roleModal.value = false
        } else {
          this.$Message.warning(res.msg)
        }
      }).catch(err => {
        this.$Message.error('操作失败,服务器失败')
      })
    },
    /**
       * 删除角色
       */
    removeRole (data) {
      deleteRole(data).then(res => {
        if (res.code === 200) {
          this.$Message.info(res.msg)
          this.listRoleAllByPage()
        } else {
          this.$Message.warning(res.msg)
        }
      }).catch(err => {
        this.$Message.error('添加失败,服务器失败')
      })
    },
    /**
       * 取消添加角色
       *
       * */
    addCancel () {
      this.$refs.role.resetFields()
      this.roleModal.value = false
    },
    /**
       * 打开窗口
       * */
    openModal (type, row) {
      this.roleModal.value = true
      this.roleModal.title = type === 'add' ? '添加角色' : '编辑角色'
      this.roleModal.type = type
      if (row.name !== undefined) {
        row.name = row.name.replace('ROLE_', '')
      }
      this.role = row
    },
    /**
       * 查询角色集合
       */
    listRoleAllByPage () {
      this.roleList = []
      let data = {
        'current': this.page.pageNum,
        'size': this.page.pageSize
      }
      selectRoleAllByPage(data).then(res => {
        const data = res
        if (data.code === 200) {
          this.page.total = data.data.total
          this.roleList = data.data.records
        }
      })
    },

    /**
       * 获取菜单树
       */
    getPerTree (row) {
      this.menuTree = []
      getRolePerTree(row.id).then(res => {
        if (res.code === 200) {
          this.selectRoleId = row.id
          this.menuTree = this.createTree(res.data)
        }
      })
      this.roleMenuModal.title = '分配 ' + row.name + ' 的菜单权限'
      this.roleMenuModal.value = true
    },
    /**
       * 封装部门数
       * @param list list
       */
    createTree (list) {
      if (list === undefined) {
        return []
      }
      let tree = []
      list.forEach(v => {
        tree.push({
          title: v.title,
          expand: true,
          staffs: [],
          name: v.name,
          icon: v.icon,
          checked: v.checked,
          id: v.id,
          children: this.createTree(v.children),
          render: (h, { root, node, data }) => {
            return h('span', {
              style: {
                display: 'inline-block',
                width: '100%'
              }
            }, [
              h('span', [
                h('Icon', {
                  props: {
                    type: data.icon
                  },
                  style: {
                    marginRight: '10px'
                  }
                }),
                h('span', data.title)
              ])
            ])
          }
        })
      })
      return tree
    },
    // 操作搜索框
    dropDown () {
      if (this.drop) {
        this.dropDownContent = '展开'
        this.dropDownIcon = 'ios-arrow-down'
      } else {
        this.dropDownContent = '收起'
        this.dropDownIcon = 'ios-arrow-up'
      }
      this.drop = !this.drop
    },
    // 清空多选
    clear () {
      this.$refs.table.selectAll(false)
    },
    pageChange (num) {
      this.page.pageNum = num
      this.selectUserAllByPage()
    },
    pageSizeChange (size) {
      this.page.pageSize = size
      this.selectUserAllByPage()
    }
  }

}
</script>

<style>
  .operation Button {
    margin: 8px;
  }

</style>
